package script

import (
	"context"
	"gitee.com/kmyss/gf-ex/yscmd"
	"gitee.com/kmyss/gf-ex/yslog"
	"gitee.com/kmyss/ys-cli/internal/model"
	"gitee.com/kmyss/ys-cli/internal/service"
	"github.com/gogf/gf/v2/os/gcmd"
)

type Builder struct {
	yscmd.CommandBuilderCore
}

func (b *Builder) Init(ctx context.Context) {
	b.CommandBuilderCore.Init(ctx)
	b.C.Use = "script"
	b.C.Short = "执行项目 scripts 目录中的脚本"

	b.C.Run = b.run
	b.addFlag()
}

func (b *Builder) addFlag() {
	b.SetFlags(&yscmd.FlagDebugBuilder{}, &FlagScriptPathBuilder{})
}

func (b *Builder) run(c *yscmd.Command) {
	cmdStr := b.getScript(c)

	err := service.Script().Run(c.Context(), &model.ScriptRunInput{
		Script: cmdStr,
		Path:   FlagScriptPath(c.Context()).Get(),
	})
	if err != nil {
		yslog.Error(err)
		yscmd.CmdWait(c.Context())
		return
	}

}

func (b *Builder) getScript(c *yscmd.Command) string {
	args := gcmd.GetArgAll()
	cmdStr := ""
	for i, arg := range args {
		if arg == c.Use {
			cmdStr = gcmd.GetArg(i + 1).String()
			break
		}
	}
	return cmdStr
}
